﻿using System;
using System.IO;
using System.Xml;
using SCRUM.Core.Configuration;

namespace SCRUM.Core.DataProviders
{
    /// <summary>
    /// Provider for commands taken from XML file
    /// </summary>
    public static class CommandResources
    {
        /// <summary>
        /// XML document
        /// </summary>
        private static XmlDocument doc;

        /// <summary>
        /// Initializes the <see cref="CommandResources"/> class.
        /// </summary>
        static CommandResources() 
        {
            doc = new XmlDocument();
            doc.Load(Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory + ConfigManager.CurrentConfig.DBProviderXml,
                String.Format("{0}.xml", ProviderFactory.Provider.Name))); 
        }

        /// <summary>
        /// Gets the command by XPath location.
        /// </summary>
        /// <param name="location">The XPath location.</param>
        /// <returns>Command text</returns>
        public static string GetCommand(string location)
        {
            XmlNode commandNode = doc.SelectSingleNode("/commands/" + location);
            return commandNode.InnerText;
        }

        /// <summary>
        /// Gets the command with order by clause concatenated at the end
        /// </summary>
        /// <param name="queryID">The query ID.</param>
        /// <param name="sortColumn">The sort column.</param>
        /// <returns></returns>
        public static string GetCommand(string queryID, string sortColumn)
        {
            return String.Format("{0} ORDER BY {1}",GetCommand(queryID),sortColumn);
        }

		/// <summary>
		/// Gets the command.
		/// </summary>
		/// <param name="location">The location.</param>
		/// <param name="pageCount">The page count.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <returns></returns>
        public static string GetCommand(string location,int pageCount, int pageSize)
        {
            XmlNode commandNode = doc.SelectSingleNode("/commands/" + location);

            string command = commandNode.InnerText;

            if ( pageCount != -1 ) 
			{
                int rowStart = (pageCount - 1) * pageSize + 1;
                int rowEnd = pageCount * pageSize;

                command = String.Format(@"
                    WITH SelectedValues AS ({0})
                    SELECT * FROM SelectedValues
                    WHERE RowNum BETWEEN {1} AND {2}"
                    ,command,rowStart,rowEnd);
            }
            return command;
        }
    }
}
